<script setup lang="tsx">
import {
  pagePointsOrderApi,
  getExportPointsExcelApi,
  adminGetExportPointsExcelApi,
  adminPagePointsOrderApi
} from '@/api/Order'
import { businessListApi } from '@/api/merchantManagement'
import Detail from './components/Detail.vue'
import { ElButton, ElMessageBox, ElMessage } from 'element-plus'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useI18n } from '@/hooks/web/useI18n'
import { useTable } from '@/hooks/web/useTable'
import { formatTime } from '@/utils'
import { IntegralOrderStateDict, dictToList, IntegralOrderStateShowDict } from '@/utils/dict'
import { hasPermission as hasPermis } from '@/components/Permission/src/utils'
import { useRoute } from 'vue-router'
import { useUserStore } from '@/store/modules/user'
const userStore = useUserStore()
const { query } = useRoute()

const { t } = useI18n()

const activeTab = ref(0)
let tabs = ref([
  {
    label: '全部',
    value: 0
  },
  {
    label: '待核销',
    value: 2
  },
  {
    label: '已完成',
    value: 3
  },
  {
    label: '已关闭',
    value: 4
  }
])

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const api = userStore.userInfo.roles.includes('商家')
      ? adminPagePointsOrderApi
      : pagePointsOrderApi
    const res = await api({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      orderState: unref(activeTab) === 0 ? '' : unref(activeTab),
      activeId: unref(query.id as any),
      agent1Mobile: unref(query.mobile as any),
      ...unref(searchParams)
    })
    return {
      list: res.data.list || [],
      total: res.data.total || 0
    }
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList } = tableMethods

const searchRef = ref()

const tabChange = (v) => {
  searchRef.value[0].reset()
  activeTab.value = v
  currentPage.value = 1
  searchParams.value = {}
  getList()
}

const getBusinessList = async () => {
  if (!hasPermis('GET /business/page')) {
    allSchemas.searchSchema.at(8)!.hidden = true
    return []
  }
  const res = await businessListApi({
    pageNum: 1,
    pageSize: 9999
  })
  return res.data.list?.map((v) => ({
    label: v.businessShortName,
    value: v.id
  }))
}

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'id',
    label: 'ID',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'orderNo',
    label: '订单编号',
    search: {
      componentProps: {
        placeholder: '请输入订单编号'
      }
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'activeTitle',
    label: '商品名称',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'orderUserMobile',
    label: '下单人',
    search: {
      componentProps: {
        placeholder: '请输入下单人手机号'
      }
    },
    form: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <div>{row.orderMobile}</div>
              <div>{row.orderNickName}</div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'orderPrice',
    label: '商品金额',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'orderNum',
    label: '数量',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'payPrice',
    label: '支付积分',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'orderState',
    label: '状态',
    search: {
      component: 'Select',
      componentProps: {
        options: dictToList(IntegralOrderStateDict)
      }
    },
    form: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <span>{row.orderState && IntegralOrderStateShowDict[row.orderState]}</span>
            </>
          )
        }
      }
    }
  },
  {
    field: 'orderTime',
    label: '下单时间',
    search: {
      component: 'DatePicker',
      componentProps: {
        type: 'datetimerange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'businessName',
    label: '所属商家',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      hidden: userStore.userInfo.roles.includes('商家')
    }
  },
  {
    field: 'businessId',
    label: '所属商家',
    search: {
      hidden: userStore.userInfo.roles.includes('商家'),
      component: 'Select',
      optionApi: async () => getBusinessList()
    },
    form: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'merchantName',
    label: '核销商户',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      width: 100,
      slots: {
        default: (data: any) => {
          const row = data.row
          return (
            <>
              <ElButton type="primary" link onClick={() => details(row)}>
                查看详情
              </ElButton>
            </>
          )
        }
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const searchParams = ref({})
const setSearchParams = (params: any) => {
  const { orderTime, ...rest } = params
  let orderTimeStart, orderTimeEnd
  if (orderTime && orderTime.length > 0) {
    orderTimeStart = orderTime[0]
    orderTimeEnd = orderTime[1]
  }
  currentPage.value = 1
  searchParams.value = {
    orderTimeStart,
    orderTimeEnd,
    ...rest
  }
  getList()
}

const showDrawer = ref(false)

const detailId = ref(0)

const details = async (row: any) => {
  detailId.value = row.id
  showDrawer.value = true
}
let selecteId = []
const selectionChange = (e) => {
  selecteId = []
  e.forEach((item) => {
    selecteId.push(item.id)
  })
}

const handleDownload = async (params: any) => {
  const { orderTime, ...rest } = params
  let orderTimeStart, orderTimeEnd
  if (orderTime && orderTime.length > 0) {
    orderTimeStart = orderTime[0]
    orderTimeEnd = orderTime[1]
  }
  const currentDate = new Date()
  const time = formatTime(currentDate, 'yyyyMMddHHmmss')
  const num = Math.floor(Math.random() * 900000) + 100000
  const orderState = unref(activeTab) === 0 ? '' : unref(activeTab)
  const api = userStore.userInfo.roles.includes('商家')
    ? adminGetExportPointsExcelApi
    : getExportPointsExcelApi
  const res = await api({
    orderState,
    orderTimeStart,
    orderTimeEnd,
    ...rest
  })
  const correctMimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  const url = window.URL.createObjectURL(new Blob([res.data], { type: correctMimeType }))
  let link = document.createElement('a')
  link.href = url
  link.download = `积分订单明细${time}${num}`
  link.style.display = 'none'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}
</script>

<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="flex-[3] ml-20px">
      <ElTabs v-model="activeTab" @tab-change="tabChange">
        <ElTabPane v-for="item in tabs" :key="item.value" :label="item.label" :name="item.value">
          <Search
            ref="searchRef"
            :schema="allSchemas.searchSchema"
            show-download
            @download="handleDownload"
            @reset="setSearchParams"
            @search="setSearchParams"
          />
          <Table
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :columns="allSchemas.tableColumns"
            :data="dataList"
            :loading="loading"
            :expand="true"
            @register="tableRegister"
            @selection-change="selectionChange"
            :pagination="{
              total
            }"
          />
        </ElTabPane>
      </ElTabs>
    </ContentWrap>

    <ElDrawer
      title="订单详情"
      v-model="showDrawer"
      direction="rtl"
      size="650px"
      @close="showDrawer = false"
    >
      <Detail v-if="showDrawer" :id="detailId" />
    </ElDrawer>
  </div>
</template>
